package pub.wkq.auth.controller;


import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import pub.wkq.api.controller.intercept.JWTCurrentUserInterceptor;
import pub.wkq.auth.service.AdminService;
import pub.wkq.bo.AdminBO;
import pub.wkq.common.base.BaseInfoProperties;
import pub.wkq.common.result.JSONResult;
import pub.wkq.common.result.ResponseStatusEnum;
import pub.wkq.common.utils.JWTUtils;
import pub.wkq.common.utils.SerializationUtils;
import pub.wkq.pojo.Admin;
import pub.wkq.vo.AdminVO;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * <p>
 * 慕聘网运营管理系统的admin账户表，仅登录，不提供注册 前端控制器
 * </p>
 *
 * @author 王开琦
 * @since 2023-06-05
 */
@RestController
@RequestMapping("/admin")
public class AdminController extends BaseInfoProperties {
    @Resource
    private AdminService adminService;
    @Resource
    private JWTUtils jwtUtils;

    @PostMapping("/login")
    public JSONResult login(@Valid @RequestBody AdminBO adminBO) {
        //执行登录判断用户是否存在
        Boolean isExist = adminService.adminLogin(adminBO);
        if (!isExist) {
            return JSONResult.errorCustom(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }
        //登录成功之后获得 admin 信息
        Admin admin = adminService.getAdminInfo(adminBO);

        String adminToken = jwtUtils.createJwtWithPrefix(SerializationUtils.serializeObject(admin), (long) (60 * 60 * 24 * 7), TOKEN_ADMIN_PREFIX);
        return JSONResult.ok(adminToken);
    }

    @GetMapping("/info")
    public JSONResult info( String token) {
        if (token == null || token.equals("")) {
            return JSONResult.errorCustom(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }
        String adminToken = token.split("@")[1];
        String adminJson = jwtUtils.checkJwt(adminToken);
        Admin admin = SerializationUtils.deserializeObject(adminJson, Admin.class);
        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(admin, adminVO);
        return JSONResult.ok(adminVO);
    }

    @PostMapping("/logout")
    public JSONResult logout(){
        return JSONResult.ok();
    }
 }

